package com.starblink.android.basic.util

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.RectF
import android.view.*
import com.starblink.basic.autosize.utils.ScreenUtils

object PopupWindowUtils {


    // 需要点击事件传递时 anchorRect不为空
    @SuppressLint("ClickableViewAccessibility")
    inline fun getNormalPopWindow(
        context: Activity,
        anchorView: View,
        parent: ViewGroup,
        anchorRect: RectF?,
        dismissClickView :View?,
        crossinline dismissCallBack: () -> Unit
    ): CustomPopupWindow {
        //设置PopupWindow的PopupView、长、宽,focusable设置是否获取焦点
        val popupWindow = CustomPopupWindow(
            anchorView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ScreenUtils.getRawScreenSize(context)[1],
            true
        )
        //覆盖状态栏
        popupWindow.isClippingEnabled = false
        //拦截所有事件在popupWindow
        popupWindow.isTouchable = true

//        popupWindow.isOutsideTouchable = true
//        popupWindow.isFocusable = true

        popupWindow.setTouchInterceptor { _, motionEvent ->
            if (anchorRect?.contains(motionEvent.x, motionEvent.y) == true
            ) {
                context.window.decorView.dispatchTouchEvent(motionEvent)
                if (motionEvent.action == MotionEvent.ACTION_UP) {
                    popupWindow.dismiss()
                    dismissCallBack()
                }
                true
            }
            false
        }
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0)

        dismissClickView?.setOnClickListener {
            popupWindow.dismiss()
            dismissCallBack()
        }


        return popupWindow
    }
}